import React, { useEffect, useState, useCallback, useRef } from 'react';
import layout from '../common/layout';
import './index.less';

import { Table, Input, Button, Pagination, message, Modal, Row } from 'antd';
import { userListApi } from '../../apis/homeApi';

function UserList({ roleList, history }) {
  const [data, setData] = useState([]),
    columns = [
      {
        title: '用户编码',
        dataIndex: 'id',
        width: 120,
      },
      {
        title: '用户名',
        dataIndex: 'name',
        width: 120,
      },
      {
        title: '用户部门',
        dataIndex: 'dept',
        width: 120,
      },
      {
        title: '用户职位',
        dataIndex: 'duties',
        width: 120,
      },
      {
        title: '用户电话',
        dataIndex: 'phone',
        width: 120,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        width: 120,
      },
      {
        title: '操作',
        key: 'opt',
        width: 120,
        render: function (row) {
          return (
            <>
              <Button
                size="small"
                onClick={btnEvt.bind(null, 'edit', row)}
                type="link"
              >
                编辑
              </Button>
              <Button
                size="small"
                onClick={btnEvt.bind(null, 'delete', row)}
                type="link"
              >
                删除
              </Button>
            </>
          );
        },
      },
    ],
    [loading, setLoading] = useState(false),
    contentNode = useRef(),
    [tableHei, setTableHei] = useState(300),
    [name, setName] = useState(''),
    [total, setTotal] = useState(0),
    [page, setPage] = useState(1),
    [size, setSize] = useState(20);

  const getUserList = useCallback(async () => {
    try {
      setLoading(true);
      let result = await userListApi({ page, size, name });
      if (result.code === 200) {
        setData((result.data.rows || []).map(it => ({ ...it, key: it.id })));
        setTotal(result.data.total || 0);
      } else {
        message.error(result.msg || '获取数据失败');
      }
    } catch (error) {
      message.error('获取数据失败，请重试');
    } finally {
      setLoading(false);
    }
  }, [page, size, name]);

  useEffect(() => {
    // getUserList()

    setTableHei(contentNode.current.clientHeight - 16 - 39);
  }, []);

  useEffect(() => {
    getUserList();
  }, [page, size]);

  function judgeRight(myRight, cb) {
    let nowRole = roleList.find((item) => item.id === 'SYSTEM-01-01');

    // 通过菜单找到用户对应的权限，如果用户有对应的菜单权限，然后对比是否有当前按钮需要的具体权限
    if (!!nowRole && nowRole.role.includes(myRight)) {
      cb();
    } else {
      message.warning('您暂时没有这个操作权限');
    }
  }

  function btnEvt(type, row) {
    switch (type) {
      case 'new':
        judgeRight('C', function () {
          history.push('/user/edit');
        });
        break;
      case 'edit':
        judgeRight('U', function () {
          history.push({ pathname: '/user/edit', state: { id: row.id } });
        });

        break;
      case 'delete':
        judgeRight('D', function () {
          Modal.confirm({
            title: '删除确认？',
            content: `您确定要删除【${row.name}】用户信息，删除以后将不会保存用户信息，确定要删除？`,
            onOk: function () {
              message.warning('删除用户');
            },
          });
        });
        break;
      default:
        break;
    }
  }

  return (
    <div className="page-layout">
      <header>
        <Input
          placeholder="请输入姓名"
          value={name}
          onChange={(evt) => {
            setName(evt.target.value);
          }}
        />
        <Button onClick={getUserList} type="primary">
          查询
        </Button>
        <Button onClick={btnEvt.bind(null, 'new')}>新增</Button>
      </header>
      <article ref={contentNode}>
        <Table
          columns={columns}
          dataSource={data}
          size="small"
          loading={loading}
          scroll={{ y: tableHei }}
          pagination={false}
        />
      </article>
      <footer>
        <Pagination
          size="small"
          total={total}
          current={page}
          pageSize={size}
          onChange={function (_page, _size) {
            setPage(_page);
            setSize(_size);
          }}
          pageSizeOptions={[20, 50, 100, 150]}
          showSizeChanger
          showQuickJumper
        />
      </footer>
    </div>
  );
}

export default layout(UserList);
